package com.css.zfzx.fxpg.modules.preestimate.result.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.fxpg.common.utils.BeanUtil;
import com.css.zfzx.fxpg.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.fxpg.common.utils.LocationUtil;
import com.css.zfzx.fxpg.modules.preestimate.result.repository.FxPreestimateResultNativeRepository;
import com.css.zfzx.fxpg.modules.preestimate.result.repository.FxPreestimateResultRepository;
import com.css.zfzx.fxpg.modules.preestimate.result.repository.entity.FxPreestimateResultEntity;
import com.css.zfzx.fxpg.modules.preestimate.result.service.FxPreestimateResultService;
import com.css.zfzx.fxpg.modules.preestimate.result.viewobjects.FxPreestimateResultQueryParams;
import com.css.zfzx.fxpg.modules.preestimate.result.viewobjects.FxPreestimateResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.io.WKTReader;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author leon
 * @date 2020-11-19
 */
@Service
@Slf4j
public class FxPreestimateResultServiceImpl implements FxPreestimateResultService {

    @Autowired
    private FxPreestimateResultRepository fxPreestimateResultRepository;
    @Autowired
    private FxPreestimateResultNativeRepository fxPreestimateResultNativeRepository;

    private static GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
    private static WKTReader reader = new WKTReader(geometryFactory);

    @Override
    public JSONObject queryFxPreestimateResults(FxPreestimateResultQueryParams queryParams, int curPage, int pageSize) {
        Page<FxPreestimateResultEntity> fxPreestimateResultPage = this.fxPreestimateResultNativeRepository.queryFxPreestimateResults(queryParams, curPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(fxPreestimateResultPage);
        return jsonObject;
    }


    @Override
    public FxPreestimateResultEntity getFxPreestimateResult(String id) {
        FxPreestimateResultEntity fxPreestimateResult = this.fxPreestimateResultRepository.findById(id).orElse(null);
        return fxPreestimateResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxPreestimateResultEntity saveFxPreestimateResult(FxPreestimateResultEntity fxPreestimateResult) {
        String uuid = UUIDGenerator.getUUID();
        fxPreestimateResult.setId(uuid);
        fxPreestimateResult.setCreateUser(PlatformSessionUtils.getUserId());
        fxPreestimateResult.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        String longitude = fxPreestimateResult.getLongitude().toString();
        String latitude = fxPreestimateResult.getLatitude().toString();
        if (StringUtils.isNotBlank(longitude) && StringUtils.isNotBlank(latitude)) {
            //String province = LocationUtil.getLocationInfoByTD(fxPreestimateResult.getLongitude(), fxPreestimateResult.getLatitude()).get("province");
            String province = LocationUtil.getGPositionByTD(fxPreestimateResult.getLongitude(), fxPreestimateResult.getLatitude()).get("province");
            fxPreestimateResult.setProvince(province);
        }
        /*try {
            Geometry geomtry = reader.read("POINT(" + longitude + " " + latitude + ")");
            fxPreestimateResult.setGeoPoint(geomtry);
        } catch (ParseException e) {
            log.error(e.getMessage(), e);
        }*/
        this.fxPreestimateResultRepository.save(fxPreestimateResult);
        return fxPreestimateResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxPreestimateResultEntity updateFxPreestimateResult(FxPreestimateResultEntity fxPreestimateResult) {
        fxPreestimateResult.setUpdateUser(PlatformSessionUtils.getUserId());
        fxPreestimateResult.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        // 经纬度变化改变省
        //String province = LocationUtil.getLocationInfoByTD(fxPreestimateResult.getLongitude(), fxPreestimateResult.getLatitude()).get("province");
        String province = LocationUtil.getGPositionByTD(fxPreestimateResult.getLongitude(), fxPreestimateResult.getLatitude()).get("province");
        fxPreestimateResult.setProvince(province);
        /*try {
            String longitude = fxPreestimateResult.getLongitude().toString();
            String latitude = fxPreestimateResult.getLatitude().toString();
            Geometry geomtry = reader.read("POINT(" + longitude + " " + latitude + ")");
            fxPreestimateResult.setGeoPoint(geomtry);
        } catch (ParseException e) {
            log.error(e.getMessage(), e);
        }*/
        String id = fxPreestimateResult.getId();
        FxPreestimateResultEntity one = fxPreestimateResultRepository.findById(id).get();
        BeanUtil.copyPropertiesIgnoreNull(fxPreestimateResult, one);
        this.fxPreestimateResultRepository.save(one);
        return fxPreestimateResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteFxPreestimateResults(List<String> ids) {
        List<FxPreestimateResultEntity> fxPreestimateResultList = this.fxPreestimateResultRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(fxPreestimateResultList) && fxPreestimateResultList.size() > 0) {
            for (FxPreestimateResultEntity fxPreestimateResult : fxPreestimateResultList) {
                this.fxPreestimateResultRepository.delete(fxPreestimateResult);
            }
        }
    }

    @Override
    public String importExcel(MultipartFile file) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置解析从第1+1+1行开始
            params.setTitleRows(1);
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<FxPreestimateResultVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), FxPreestimateResultVO.class, params);
            List<FxPreestimateResultVO> list = result.getList();
            // 批量新增
            this.saveExcel(list);
            returnMsg.append("成功导入" + result.getList().size() + "条，失败" + result.getFailList().size() + "条<br/>");
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<FxPreestimateResultVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    FxPreestimateResultVO resultVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + resultVO.getRowNum() + "行" + resultVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "导入失败，请检查数据正确性";
        }
    }

    @Override
    public String exportExcel(FxPreestimateResultQueryParams queryParams, HttpServletResponse response) {
        try {
            String estimate=queryParams.getEstimate();

            List<FxPreestimateResultEntity> resultEntities = fxPreestimateResultNativeRepository.getFxPreestimateResults(queryParams);
            // 深拷贝
            ArrayList<FxPreestimateResultVO> vos = new ArrayList<>();
            for (FxPreestimateResultEntity resultEntity : resultEntities) {
                FxPreestimateResultVO vo = new FxPreestimateResultVO();
                BeanUtils.copyProperties(resultEntity, vo);
                vos.add(vo);
            }
            // 导出
            EasyPoiExcelUtil.exportExcel(vos, "预评估结果数据统计", "预评估结果数据", FxPreestimateResultVO.class, "预评估结果数据.xlsx", response);
            return "导出成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    @Override
    public String exportSpatialLocationExcel(FxPreestimateResultQueryParams queryParams, HttpServletResponse response) {
        try {
            List<FxPreestimateResultEntity> resultEntities = fxPreestimateResultNativeRepository.getFxPreestimateResults(queryParams);
            // 深拷贝
            ArrayList<FxPreestimateResultVO> vos = new ArrayList<>();
            for (FxPreestimateResultEntity resultEntity : resultEntities) {
                FxPreestimateResultVO vo = new FxPreestimateResultVO();
                BeanUtils.copyProperties(resultEntity, vo);
                vos.add(vo);
            }
            // 导出
            EasyPoiExcelUtil.exportExcel(vos, "预评估结果数据检索与展示-空间位置选择查询", "预评估结果数据检索与展示-空间位置选择查询", FxPreestimateResultVO.class, "预评估结果数据检索与展示-空间位置选择查询.xlsx", response);
            return "导出成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    /**
     * 保存Excel数据
     *
     * @param list
     */
    private void saveExcel(List<FxPreestimateResultVO> list) {
        FxPreestimateResultEntity resultEntity = new FxPreestimateResultEntity();
        for (FxPreestimateResultVO resultVO : list) {
            // VO数据拷贝到Entity中
            BeanUtils.copyProperties(resultVO, resultEntity);
            this.saveFxPreestimateResult(resultEntity);
        }
    }

    @Override
    public List<FxPreestimateResultEntity> getFxPreestimateResults(FxPreestimateResultQueryParams queryParams) {
        List<FxPreestimateResultEntity> fxPreestimateResults = this.fxPreestimateResultNativeRepository.getFxPreestimateResults(queryParams);
        for (int i = 0; i < fxPreestimateResults.size(); i++) {
            FxPreestimateResultEntity fxPreestimateResultEntity = fxPreestimateResults.get(i);
            double longitude = fxPreestimateResultEntity.getLongitude(), latitude = fxPreestimateResultEntity.getLatitude();
            Map<String, String> map = LocationUtil.getGPositionByTD(longitude, latitude);
            String province = map.get("province"), city = map.get("city"), area = map.get("county");
            fxPreestimateResultEntity.setProvince(province + "-" + city + "-" + area);
        }
        return fxPreestimateResults;
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public JSONObject querySpatialLocation(FxPreestimateResultQueryParams queryParams, int curPage, int pageSize) {
        Page<FxPreestimateResultEntity> fxPreestimateResultPage = this.fxPreestimateResultNativeRepository.querySpatialLocation(queryParams, curPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(fxPreestimateResultPage);
        return jsonObject;
    }

    @Override
    public JSONObject querySpatialLocationByBoundary(FxPreestimateResultQueryParams queryParams, int curPage, int pageSize) {
        Page<FxPreestimateResultEntity> fxPreestimateResultPage = this.fxPreestimateResultNativeRepository.querySpatialLocationByBoundary(queryParams, curPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(fxPreestimateResultPage);
        return jsonObject;
    }

}
